﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections;
using Microsoft.Xna.Framework.Content;

namespace MobMentality.Map
{
	/*
	 * This is essentially a drawing class
	 * it holds tiles and draws them
	 * based on the offset of the camera
	 */
	class MapDraw : IMapDraw
	{
		Dictionary<string,Texture2D> images;
		string[,] tiles;
		int numRows;
		int numColumns;
		int tileWidth;
		int tileHeight;

		public int ScreenWidth
		{
			get;
			set;
		}

		public int ScreenHeight
		{
			get;
			set;
		}

		/*
		 * rows - number of rows in the map
		 * columns - number of columns in the map
		 * tileWidth - width of EVERY tile (in px)
		 * tileHeight - height of EVERY tile (in px)
		 * imageFilenames - connects level editor names to filenames of images
		 * content - allows us to load textures (sprites)
		 */
		public MapDraw(int rows, int columns, int tileWidth, int tileHeight, Dictionary<string,string> imageFilenames, ContentManager content, int screenWidth, int screenHeight)
		{
			//initialize arrays
			images = new Dictionary<string, Texture2D>(imageFilenames.Count);
			tiles = new string[rows, columns];
			numRows = rows;
			numColumns = columns;
			ScreenWidth = screenWidth;
			ScreenHeight = screenHeight;

			//set tile dimensions
			this.tileWidth = tileWidth;
			this.tileHeight = tileHeight;

			//store image data for each type of tile
			foreach(string name in imageFilenames.Keys)
			{
				images.Add(name, content.Load<Texture2D>(imageFilenames[name]));
			}
		}

		public void AddTile(int row, int column, string name)
		{
			tiles[row, column] = name;
		}

		/*
		 * cameraPosition - Gives the offset of the user's viewport to 0,0 on the map
		 * spriteBatch - We need to pass spriteBatch down to Draw becase 
		 *	1) its faster to use one sprite batch draw
		 *	2) need to use only one sprite batch to control the order sprites are displayed in
		 */
		public void Draw(Vector2 cameraPosition, SpriteBatch spriteBatch, List<Point> captured)
		{
			Rectangle destinationRect = new Rectangle(-(int)cameraPosition.X, -(int)cameraPosition.Y,
														tileWidth, tileHeight);

			for(int r = 0; r < numRows; r++)
			{
				for (int c = 0; c < numColumns; c++)
				{
					if (destinationRect.X >= -tileWidth && destinationRect.Y >= -tileHeight && destinationRect.X < ScreenWidth && destinationRect.Y < ScreenHeight)
					{
						spriteBatch.Draw(images[tiles[r, c]], destinationRect, Color.White);

						if (captured.Contains(new Point(c, r)))
						{
							spriteBatch.Draw(images["captured"], destinationRect, Color.White);
						}
					}

					destinationRect.X += tileWidth;
				}
				destinationRect.X = -(int)cameraPosition.X;
				destinationRect.Y += tileHeight;
			}
		}
	}
}